package org.rujue.modules.sys.service;

import java.util.List;

import org.checkerframework.checker.units.qual.A;
import org.rujue.common.config.Global;
import org.rujue.common.utils.StringUtils;
import org.rujue.modules.sys.utils.SysUtils;
import org.rujue.modules.sys.entity.SysFile;
import org.rujue.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.rujue.common.persistence.Page;
import org.rujue.common.service.CrudService;
import org.rujue.modules.sys.entity.SysNotice;
import org.rujue.modules.sys.dao.SysNoticeDao;

/**
 * 通知公告Service
 * @author Mr.xu
 * @version 2023-11-14
 */
@Service
@Transactional(readOnly = true)
public class SysNoticeService extends CrudService<SysNoticeDao, SysNotice> {
	@Autowired
	private SysFileService sysFileService;


	public SysNotice get(String id) {
		return super.get(id);
	}
	
	public List<SysNotice> findList(SysNotice sysNotice) {
		List<SysNotice> list = dao.findList(sysNotice);
		for(SysNotice notice : list){
			SysFile sysFile = new SysFile();
			sysFile.setHostId(notice.getId());
			List<SysFile> sysFileList = sysFileService.findList(sysFile);
			if(sysFileList.size() > 0){
				notice.setSysFileList(sysFileList);
			}
		}
		return list;
	}
	
	public Page<SysNotice> findPage(Page<SysNotice> page, SysNotice sysNotice) {
		return super.findPage(page, sysNotice);
	}
	
	@Transactional(readOnly = false)
	public void save(SysNotice sysNotice) {
		super.save(sysNotice);
		if(sysNotice.getFile() !=null && sysNotice.getFile().getSize() > 0){
			if(sysNotice.getSysFile() != null && StringUtils.isNotBlank(sysNotice.getSysFile().getId())){
				sysFileService.delete(sysNotice.getSysFile());
			}
			SysFile entity = new SysFile();
			entity.setFile(sysNotice.getFile());
			entity.setHostId(sysNotice.getId());
			entity.setHostTable(SysUtils.TABLE_NAME_SYS_NOTICE);
			entity.setHostIds("0," + sysNotice.getId() + ",");
			sysFileService.save2Upload(entity);
			if(StringUtils.isBlank(entity.getId())){
				throw new RuntimeException("保存文件失败");
			}
			// 更新file_id值
			sysNotice.setSysFile(entity);
			sysNotice.preUpdate();
			dao.updateFileId(sysNotice);
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(SysNotice sysNotice) {
		super.delete(sysNotice);
		if(sysNotice.getSysFile()!= null && StringUtils.isNotBlank(sysNotice.getSysFile().getId())){
			sysFileService.delete(sysNotice.getSysFile());
		}
	}

}